<template>
  <div>
    <el-dialog
      :title="UploadingFileData.title"
      width="22%"
      :visible.sync="UploadingFileData.deleteDialog"
    >
      <el-form label-width="10px">
        <el-form-item label="">
          <el-upload
            class="upload-demo"
            drag
            action="2"
            multiple
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-change="uploadChange"
            :file-list="fileList"
            :auto-upload="false"
            :limit="1"
            accept=".docx, .xlsx, .pptx, .ppt, .doc, .xls, .pdf"
          >
            <i class="el-icon-upload" />
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="UploadingFileData.deleteDialog = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
      <el-dialog class="mini" :visible.sync="innerVisible" append-to-body>
        文件正在上传
        <el-progress :percentage="percentage"></el-progress>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { listTeamTree } from '@/api/fd/repository.js'
import { listTreeFolderOnlyFolder } from '@/api/fd/folder.js'
import { unity } from '@/styles/js/setIconType.js'
import axios from 'axios'
import { getToken } from '@/utils/auth'
import permissionList from '@/utils/permissionList.js'

export default {
  props: ['UploadingFileData'],

  data() {
    return {
      iconType: unity.setIconType,
      treeProps: {
        children: 'children',
        label: 'label',
        id: 'value'
      },
      options: [],
      value: '',
      treeData: [],
      checkedId: '',
      repositoryId: '',
      folderId: '',
      checked: false,
      uploadings: '',
      fileList: [],
      show: true,
      TYPE: 1,
      level: '',
      innerVisible: false,
      percentage: 12
    }
  },
  watch: {
    UploadingFileData(data) {
      this.TYPE = data.type || 1
      this.fileList = []
      this.level = data.level
    }
  },
  mounted() {
    listTeamTree({
      permission: permissionList.VISIBLE + permissionList.NEW
    }).then((res) => {
      res.data.map((item) => {
        if (!item.children) {
          item.disabled = true
        }
      })
      this.options = res.data
    })
  },
  methods: {
    // 计时器
    start() {
      this.time = setInterval(() => {
        if (this.percentage < 98) {
          this.percentage++
        } else {
          this.percentage = 98
        }
      }, 1000)
      this.$forceUpdate()
    },
    clearTime(time) {
      // 清除定时器
      clearInterval(time)
    },
    handleChange(row) {
      this.repositoryId = row[row.length - 1]
      listTreeFolderOnlyFolder({ repositoryId: row[row.length - 1] }).then(
        (res) => {
          this.treeData = res.data.data
          // this.getItem(this.treeData)
        }
      )
    },
    handleCheckChange(data, checkbox, node) {
      if (checkbox === true) {
        this.folderId = data.value
        this.$refs.treeForm.setCheckedNodes([data])
      }
    },
    handleRemove(file, fileList) {
      this.show = true
      this.fileList = []
    },
    handlePreview(file) {},
    uploadChange(file, fileList) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      const whiteList = ['docx', 'xlsx', 'pptx', 'ppt', 'doc', 'xls', 'pdf']
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$refs.upload.uploadFiles = this.$refs.upload.uploadFiles.filter(
          (e) => {
            if (e.uid != file.uid) {
              return true
            }
          }
        )
        this.$message.warning(
          '上传文件只能是 docx、xlsx、pptx、ppt、doc、xls、jpg、jpeg、png、pdf格式'
        )
        return
      }
      this.fileList = fileList
      if (fileList) {
        this.show = false
      }
    },
    confirm() {
      const formData = new FormData()
      // 目标库id
      const repositoryId = 3
      this.UploadingFileData.deleteDialog = false
      this.innerVisible = true
      this.start()
      if (this.TYPE === 2) {
        formData.append('folderId', 0)
        formData.append('repositoryId', repositoryId)
        formData.append('documentCode', this.UploadingFileData.documentItem)
        formData.append('level', this.level)
        this.fileList.forEach((file) => {
          formData.append('file', file.raw)
        })
        this.newUploadDocument(formData)
      } else {
        formData.append('documentId', this.UploadingFileData.documentItem)
        formData.append('level', this.level)
        this.fileList.forEach((file) => {
          formData.append('file', file.raw)
        })
        this.redoUploadDocument(formData)
      }
    },
    newUploadDocument(formData) {
      axios({
        url: process.env.VUE_APP_BASE_API + '/api/fd/document/upload',
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data;charset=utf-8',
          Authorization: getToken()
        }
      })
        .then((res) => {
          if (res.data.code === 1) {
            const newObj = {
              update: res.data.data,
              row: this.UploadingFileData
            }
            this.$emit('uploadingdata', newObj)
            this.show = true
            this.percentage = 100
            this.clearTime()
            this.innerVisible = false
            this.$message.success('上传成功')
            // this.$refs.upload.clearFiles()
            // this.$parent.getList()
          } else {
            this.$message.error('上传失败')
            this.percentage = 12
            this.clearTime()
            this.innerVisible = false
          }
        })
        .catch((e) => {
          console.log(e)
        })
    },
    redoUploadDocument(formData) {
      axios({
        url: process.env.VUE_APP_BASE_API + '/api/fd/document/replace',
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data;charset=utf-8',
          Authorization: getToken()
        }
      })
        .then((res) => {
          if (res.data.code === 1) {
            const newObj = {
              update: res.data.data,
              row: this.UploadingFileData
            }
            this.$emit('uploadingdata', newObj)
            this.show = true
            this.percentage = 100
            this.clearTime()
            this.innerVisible = false
            this.$message.success('上传成功')
            this.$refs.upload.clearFiles()
            this.$parent.getList()
          } else {
            this.$message.error('上传失败')
            this.percentage = 12
            this.clearTime()
            this.innerVisible = false
          }
        })
        .catch((e) => {
          console.log(e)
        })
    }
  }
}
</script>

<style scoped>
.aa > .el-upload-list {
  margin: -42px;
}
.upload-demo {
  width: 100%;
}
.upload-demo >>> .el-upload {
  width: 100%;
}
.upload-demo >>> .el-upload-dragger {
  width: 100%;
}
</style>
